package www.xudan.javabasedemo.model.Proxy.DynamicsProxy.horizontal;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * Created by ${XuDan} on 2020/3/23.
 */
public interface CaculateTime {
    void caculate();
}

class MethedCaculateTime implements CaculateTime {

    @Override
    public void caculate() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

class CaculateInvocationHandler implements InvocationHandler {
    private CaculateTime mCaculateTime;

    public CaculateInvocationHandler(CaculateTime mCaculateTime) {
        this.mCaculateTime = mCaculateTime;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        long start = System.currentTimeMillis();
        Object invoke = method.invoke(mCaculateTime, args);
        long end = System.currentTimeMillis();
        long l = end - start;
        System.out.println(l);
        return invoke;
    }
}

class MyProxy {
    public static Object getInstance(CaculateTime mCaculateTime) {
        return Proxy.newProxyInstance(
                mCaculateTime.getClass().getClassLoader(),
                mCaculateTime.getClass().getInterfaces(),
                new CaculateInvocationHandler(mCaculateTime)
        );
    }
}

class Client2 {
    public static void main(String[] args) {
        CaculateTime caculateTime = new MethedCaculateTime();
        CaculateTime instance = (CaculateTime) MyProxy.getInstance(caculateTime);
        instance.caculate();
    }
}
